package com.lagou.dao.impl;

import com.lagou.bean.Resume;
import com.lagou.dao.ResumeDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver;
import org.springframework.data.mongodb.core.index.TextIndexDefinition;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("resumeDao")
public class ResumeDAOImpl implements ResumeDAO {

    private String collectionName = "lg_resume_datas";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void insertResume(Resume resume) {
        mongoTemplate.insert(resume,collectionName);
    }

    @Override
    public Resume findOneByName(String name) {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(name));
        return mongoTemplate.findOne(query,Resume.class,collectionName);
    }

    @Override
    public List<Resume> findByCity(String city) {
        Query query = new Query();
        query.addCriteria(Criteria.where("city").is(city));
        return mongoTemplate.find(query,Resume.class);
    }

    @Override
    public boolean remove(String name){
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(name));
        return mongoTemplate.remove(query,collectionName).getDeletedCount() > 0L;
    }

//    @EventListener(ApplicationReadyEvent.class)
//    public void initIndicesAfterStartup(){
//        IndexOperations indexOps = mongoTemplate.indexOps(Resume.class);
//        MongoMappingContext mappingContext = new MongoMappingContext();
//        mappingContext.setAutoIndexCreation(true);
//        MongoPersistentEntityIndexResolver resolver = new MongoPersistentEntityIndexResolver(mappingContext);
//        resolver.resolveIndexFor(Resume.class).forEach(indexOps::ensureIndex);
//    }
}
